# -*- coding: utf-8 -*-
"""
Created on Wed Apr 10 10:07:06 2024

@author: 刘翼
"""

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread(r"C:\Users\Public\opencv\Figure\bird.jpg") # 读取图像
# Roberts算子
grayImage = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)  # 灰度化处理图像
# Roberts算子
kernelx = np.array([[-1, 0], [0, 1]], dtype=int)
kernely = np.array([[0, -1], [1, 0]], dtype=int)
x = cv2.filter2D(grayImage, cv2.CV_16S, kernelx)
y = cv2.filter2D(grayImage, cv2.CV_16S, kernely)
# 转uint8
absX = cv2.convertScaleAbs(x)  #数据类型转换
absY = cv2.convertScaleAbs(y)
Roberts = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)  #图像融合，0不需要修正（修正系数）

# Prewitt算子
kernelx = np.array([[1, 1, 1],[0, 0, 0],[-1, -1, -1]],dtype=int)
kernely = np.array([[-1, 0, 1],[-1, 0, 1],[-1, 0, 1]],dtype=int)
x = cv2.filter2D(grayImage,cv2.CV_16S,kernelx)
y = cv2.filter2D(grayImage,cv2.CV_16S,kernely)

absX = cv2.convertScaleAbs(x)   # 转uint8
absY = cv2.convertScaleAbs(y)
Prewitt = cv2.addWeighted(absX, 0.5, absY, 0.5, 0)

# Sobel算子
sobelX = cv2.Sobel(img,cv2.CV_16S,1,0)  # 对x求一阶导
sobelY = cv2.Sobel(img,cv2.CV_16S,0,1)  # 对y求一阶导
sobelX = cv2.convertScaleAbs(sobelX)      # 转换为uint8
sobelY = cv2.convertScaleAbs(sobelY)      # 转换为uint8
# 两幅图像叠加
sobelCombined = cv2.addWeighted(sobelX,0.5,sobelY,0.5,0) 

# Laplacian算子
# 高斯滤波
image = cv2.GaussianBlur(img,(3,3),0)
# 拉普拉斯边缘检测
laplacian = cv2.Laplacian(image,cv2.CV_16S,ksize=3)
laplacian = cv2.convertScaleAbs(laplacian)

# 显示图像

plt.subplot(231)
plt.title('Original')
plt.imshow(grayImage)
plt.axis('off')

plt.subplot(232)
plt.title('Roberts')
plt.imshow(Roberts)
plt.axis('off')


plt.subplot(233)
plt.title('prewitt')
plt.imshow(Prewitt)
plt.axis('off')

plt.subplot(234)
plt.title('Sobel Combined')
plt.imshow(sobelCombined)
plt.axis('off')

plt.subplot(235)
plt.title('Laplacian')
plt.imshow(laplacian)
plt.axis('off')

cv2.waitKey()
cv2.destroyAllWindows()
